package com.sywb.chuangyebao.utils;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.bean.AbsObject;
import com.sywb.chuangyebao.bean.UserToken;

import org.bining.footstone.bean.AbsT;
import org.bining.footstone.http.callback.JsonCallback;
import org.bining.footstone.http.model.Progress;
import org.bining.footstone.http.model.Response;
import org.bining.footstone.http.request.base.Request;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class HttpRetryCallback extends JsonCallback<AbsObject> {

    private int type; //请求类型 1:GET 2:POST 3:UPLOAD
    private String mothedUrl;
    private String aesParams;
    private HttpCallback httpCallback;

    public void cacheRequest(int type, String mothedUrl, String aesParams, HttpCallback<?> httpCallback) {
        this.type = type;
        this.mothedUrl = mothedUrl;
        this.aesParams = aesParams;
        this.httpCallback = httpCallback;
    }

    /**
     * 请求网络开始前，UI线程
     */
    @Override
    public void onStart(Request<AbsObject, ? extends Request> request) {
        super.onStart(request);
        httpCallback.onStart();
    }

    @Override
    public void onSuccess(Response<AbsObject> response) {
        AbsObject absS = response.body();
        if (absS != null) {
            httpCallback.setMsg(absS.msg);
            if (absS.isCodeSuccess()) {
                if (absS.result == null || TextUtils.isEmpty(absS.result.toString()) || absS.result.toString().length() == 0) {
                    httpCallback.onSuccess(null);
                } else {
                    try {
                        if (absS.result.toString().startsWith("{") || absS.result.toString().startsWith("[")) {
                            httpCallback.onSuccess(JSON.parseObject(absS.result.toString(), httpCallback.type));
                        } else {
                            httpCallback.onSuccess(absS.result);
                        }
                    } catch (Exception e) {
                        httpCallback.onError("");
                    }
                }
            } else {
                if (absS.code == 10001) {// 需要刷新Token
                    getSignToken();
                } else if (absS.code == 10002) {// 未登录
                    RxBus.get().post(Constants.HTTP_SSO_LOGIN, absS.getMsg());
                    httpCallback.onError("");
                } else {
                    httpCallback.onError(absS.getMsg());
                }
            }
        } else {
            httpCallback.onError("暂无数据");
        }
    }

    public void getSignToken() {
        JsonCallback jsonCallback = new JsonCallback<AbsT<UserToken>>() {
            @Override
            public void onSuccess(Response<AbsT<UserToken>> response) {
                AbsT<UserToken> absT = response.body();
                if (absT != null) {
                    httpCallback.setMsg(absT.msg);
                    if (absT.isCodeSuccess()) {
                        if (absT.result != null) {
                            SharedUtils.put(Constants.USERREFRESHTOKEN, absT.result.refresh_token);
                            SharedUtils.put(Constants.USERACCESSTOKEN, absT.result.access_token);
                            switch (type) {
                                case 1:
                                    HashMap<String, Object> getParams = JSON.parseObject(aesParams, new TypeReference<HashMap<String, Object>>() {
                                    });
                                    HttpUtils.getHttp(mothedUrl, getParams, httpCallback);
                                    break;
                                case 2:
                                    LinkedHashMap<String, Object> postParams = JSON.parseObject(aesParams, new TypeReference<LinkedHashMap<String, Object>>() {
                                    });
                                    HttpUtils.postHttp(mothedUrl, postParams, httpCallback);
                                    break;
                                case 3:
                                    List<String> pathList = JSON.parseArray(aesParams, String.class);
                                    List<File> fileList = new ArrayList<>();
                                    for (String path : pathList) {
                                        fileList.add(new File(path));
                                    }
                                    HttpUtils.uploadHttp(fileList, httpCallback);
                                    break;
                            }
                        } else {
                            httpCallback.onError("数据异常,请稍后重试.");
                        }
                    } else {
                        if (absT.code == 10002) {// 未登录
                            RxBus.get().post(Constants.HTTP_SSO_LOGIN, absT.getMsg());
                            httpCallback.onError("");
                        } else {
                            httpCallback.onError(absT.getMsg());
                        }
                    }
                } else {
                    httpCallback.onError("暂无数据");
                }
            }

            @Override
            public void onError(Response<AbsT<UserToken>> response) {
                super.onError(response);
                httpCallback.onError("请求失败");
            }
        };

        LinkedHashMap<String, Object> paramsMap = new LinkedHashMap<>();
        paramsMap.put("uid", SharedUtils.getString(Constants.USEROPENID, ""));
        paramsMap.put("refresh_token", SharedUtils.getString(Constants.USERREFRESHTOKEN, ""));
        paramsMap.put("encrypt_time", System.currentTimeMillis() / 1000);
        String paramsAES = AESUtils.encrypt(JSON.toJSONString(paramsMap));
        HttpUtils.postHttp(Constants.HTTP_SSO_REFRESHTOKEN, paramsAES, jsonCallback);
    }

    /**
     * 请求失败，响应错误，数据解析错误等，都会回调该方法， UI线程
     */
    @Override
    public void onError(Response<AbsObject> response) {
        httpCallback.onError("请求失败");
    }

    /**
     * 缓存失败的回调,UI线程
     */
    @Override
    public void onCacheSuccess(Response<AbsObject> response) {
        httpCallback.onError("缓存失败");
    }

    /**
     * 请求网络结束后，UI线程
     */
    @Override
    public void onFinish() {
        httpCallback.onFinish();
    }

    /**
     * Post执行上传过程中的进度回调，get请求不回调，UI线程
     */
    @Override
    public void uploadProgress(Progress progress) {
        super.uploadProgress(progress);
        httpCallback.onLoading(progress.currentSize, progress.totalSize, progress.date, progress.speed);
    }

    /**
     * 执行下载过程中的进度回调，UI线程
     */
    @Override
    public void downloadProgress(Progress progress) {
        super.downloadProgress(progress);
        httpCallback.onLoading(progress.currentSize, progress.totalSize, progress.date, progress.speed);
    }

}
